﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MonoTorrent.Common;
using System.Threading;
using MonoTorrent.Client;

namespace AutoNyaa.Logic
{
    public class TorrentManagerWrapper
    {
        private List<TorrentManager> _torrentManagers;
        private ClientEngine _clientEngine;
        private EngineSettings _engineSettings;
        private TorrentSettings _torrentSettings;

        public void StartTorrent(string torrentPath)
        {
            Torrent torrent = Torrent.Load(torrentPath);

            TorrentManager torrentManager = new TorrentManager(torrent, _engineSettings.SavePath, _torrentSettings);

            _clientEngine.Register(torrentManager);

            torrentManager.TorrentStateChanged += StateChanged;

            _torrentManagers.Add(torrentManager);

            torrentManager.Start();
        }

        public TorrentManagerWrapper(string downloadLocation)
        {
            _engineSettings = new EngineSettings();

            _engineSettings.GlobalMaxConnections = 1000;
            _engineSettings.GlobalMaxHalfOpenConnections = 1000;

            _torrentSettings = new TorrentSettings();

            _torrentSettings.MaxConnections = 200;

            _torrentManagers = new List<TorrentManager>();
            _engineSettings.SavePath = downloadLocation;
            _clientEngine = new ClientEngine(_engineSettings);
        }

        public void HashTorrent(TorrentManager manager)
        {
            // Note: The manager must be in the 'Stopped' state in order to perform
            // a hash check. Also, to make the sample easier the event handler
            // is not unregistered. In your application be careful you don't
            // accidentally attach a new event handler every time the torrent is hashed
            manager.PieceHashed += delegate(object o, PieceHashedEventArgs e)
            {
                int pieceIndex = e.PieceIndex;
                int totalPieces = e.TorrentManager.Torrent.Pieces.Count;
                double progress = (double)pieceIndex / totalPieces * 100.0;
                if (e.HashPassed)
                    Console.WriteLine("Piece {0} of {1} is complete", pieceIndex, totalPieces);
                else
                    Console.WriteLine("Piece {0} of {1} is corrupt or incomplete ", pieceIndex, totalPieces);

                // This shows how complete the hashing is.
                Console.WriteLine("Total progress is: {0}%", progress);

                // This shows the percentage completion of the download. This value
                // is updated as the torrent is hashed or new pieces are downloaded
                Console.WriteLine("{0}% of the torrent is complete");
            };

            // If 'true' is passed, the torrent will automatically go to the 'Downloading' or 'Seeding'
            // state once the hash check is finished. Otherwise it will return to the 'Stopped' state.
            manager.HashCheck(false);
        }

       
        public void StateChanged(object sender, TorrentStateChangedEventArgs args)
        {
            TorrentManager torrentManager = (TorrentManager)sender;
            if (args.NewState == TorrentState.Seeding)
            {
                torrentManager.Stop();
            }
        }

        public void Exit()
        {
            foreach (TorrentManager torrentManager in _torrentManagers)
            {
                if (torrentManager.State != TorrentState.Stopped && torrentManager.State != TorrentState.Stopping)
                {
                    torrentManager.Stop();
                }
            }
            foreach (TorrentManager torrentManager in _torrentManagers)
            {
                if (torrentManager.State != TorrentState.Stopped)
                {
                    Thread.Sleep(100);
                }
            }
            SaveTorrents();
        }

        private void SaveTorrents()
        {
           // throw new NotImplementedException();
        }
    }
}